<template>
  <BasicModal @register="registerModal" :footer="false">
    <div class="allPrinterBtnGroup">
        <a-button class="allPrinterBtn" type="primary" preIcon="ant-design:printer-outlined" @click="printAll">打印全部二维码</a-button>
    </div>
    <div class="printerImages">
      <div v-for="(item, index) in QrItemList" :key="index">
        <div style="text-align: center">
            <div class="test">
            <canvas ref="qrcodeCanvas" :id="`qrcode-${index}`" width="400" height="380"></canvas>
            </div>
        </div>
      </div>
    </div>
  </BasicModal>
</template>
<script lang="ts" setup>
  import QRcode from 'qrcode';
  import { BasicModal, useModal, useModalInner } from '/@/components/Modal';
  import { ref, unref, nextTick } from 'vue';
  import { QrCode, QrCodeActionType } from '/@/components/Qrcode/index';
  import LogoImg from '/@/assets/images/logo.png';
  import { CollapseContainer } from '/@/components/Container/index';
  // import { PageWrapper } from '/@/components/Page';
  import printJS from 'print-js';
  let QrItemList = ref([]);
  const [registerModal] = useModalInner((record: any) => {
    QrItemList.value = record;
    nextTick(() => {
      QrItemList.value.forEach((item, index) => {
        updateQRCode(
          'samId:' + item.id +';' +'samName:' + item.samName + ';' + 'samNum:' + item.samNum + ';' + 'samModel:' + item.model + ';' + 'samDate:' + item.samDate,
          index,
          item.samName,
          item.samNum,
          item.samDate
        );
      });
    });
  });
  const btFn = () => {
    //将canvas生成的二维码，转为base64
    const imageData = document.querySelector('#test').toDataURL('image/png');
    // Blob 下载
    base64Down('测试', imageData);
  };
  const base64Down = (fileName, base64URL) => {
    const a = document.createElement('a');
    // 将 a 标签的 download 属性设置为要下载的文件名
    a.download = fileName || 'image';
    // 创建 Blob 对象，并获取 base64 数据的 MIME 类型
    const mimeType = base64URL.match(/:(.*?);/)[1];
    // 将 base64 数据转换为字节数组
    const byteCharacters = atob(base64URL.split(',')[1]);
    const byteNumbers = new Array(byteCharacters.length);
    // 将字节数组填充到 Uint8Array 中
    for (let i = 0; i < byteCharacters.length; i++) {
      byteNumbers[i] = byteCharacters.charCodeAt(i);
    }
    const byteArray = new Uint8Array(byteNumbers);
    // 创建 Blob 对象
    const blob = new Blob([byteArray], { type: mimeType });
    // 将 Blob 对象的 URL 赋值给 a 标签的 href 属性
    a.href = URL.createObjectURL(blob);
    // 将a标签暂时添加到 body 中，触发下载
    document.body.appendChild(a);
    a.click();
    // 下载完成后，将 a 标签从 body 中移除
    document.body.removeChild(a);
  };

  const qrDiyRef = ref<Nullable<QrCodeActionType>>(null);

  function downloadDiy() {
    const qrEl = unref(qrDiyRef);
    if (!qrEl) return;
    qrEl.download('Qrcode');
  }

  //打印单张二维码
  function imagePrint() {
    //将canvas生成的二维码，转为base64
    const imageData = document.querySelector('#test').toDataURL('image/png');
    const imageUrl = base64ToImageUrl(imageData);
    printJS({
      printable: [imageUrl],
      type: 'image',
      header: 'Multiple Images',
      imageStyle: 'width:100%;',
    });
  }

  function base64ToImageUrl(base64Data) {
    const blob = dataURItoBlob(base64Data);
    return URL.createObjectURL(blob);
  }

  function dataURItoBlob(dataURI) {
    const byteString = atob(dataURI.split(',')[1]);
    const mimeString = dataURI.split(',')[0].split(':')[1].split(';')[0];
    const arrayBuffer = new ArrayBuffer(byteString.length);
    const uint8Array = new Uint8Array(arrayBuffer);

    for (let i = 0; i < byteString.length; i++) {
      uint8Array[i] = byteString.charCodeAt(i);
    }

    return new Blob([arrayBuffer], { type: mimeString });
  }

  // 函数来生成二维码
  const updateQRCode = async (content, index, value1, value2, value3) => {
    const canvas: any = document.getElementById(`qrcode-${index}`);
    console.log('canvas', canvas);
    const ctx = canvas.getContext('2d');
    ctx.clearRect(0, 0, canvas.width, canvas.height);
    // 设置背景颜色
    ctx.fillStyle = 'white';
    ctx.fillRect(800, 90, 250, 300);
    // 绘制文字
    ctx.fillStyle = 'black'; // 设置文字颜色为黑色
    ctx.font = '14px 微软雅黑';
    ctx.fillText('样品名称:' + value1, 150, 85);
    ctx.fillText('样品编号:' + value2, 150, 105);
    ctx.fillText('入库时间:' + value3, 150, 125);
    // ctx.fillText('国别:' + value4, 150, 145);

    // 绘制二维码
    const qrCodeData = await QRcode.toDataURL(content, {
      width: 250,
      height: 180,
    });
    const qrCodeImage = new Image();
    qrCodeImage.src = qrCodeData;
    qrCodeImage.onload = () => {
      ctx.drawImage(qrCodeImage, 130, 128); // 调整二维码的位置
      // ctx.drawImage(qrCodeImage, 130, 108); // 调整二维码的位置
    };
  };

  //打印全部
  const printAll = () => {
    let imageUrls = [];
    QrItemList.value.forEach((item, index) => {
      //将canvas生成的二维码，转为base64
      const imageData = document.getElementById(`qrcode-${index}`).toDataURL('image/png');
      const imageUrl = base64ToImageUrl(imageData);
      imageUrls.push(imageUrl);
    });
    printJS({
      printable: imageUrls,
      type: 'image',
      header: 'Multiple Images',
      imageStyle: 'width:100%;',
    });
  };
</script>
<style scoped>
  .qrcode-demo-item {
    width: 30%;
    margin-right: 1%;
  }
  .allPrinterBtnGroup{
    display: flex;
    justify-content: center;
  }
  .allPrinterBtn{
    margin:20px auto;
  }
  .printerImages{
    max-height: 70Vh;
    overflow:auto;
  }
</style>
